package com.wgo.precise.server.pdf;

import org.apache.log4j.Logger;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.wgo.bpot.common.removeme.Persistent;

public abstract class BasicPdfFactory<C extends Persistent> implements PdfFactory<C> {
	private static final Logger log = Logger.getLogger(BasicPdfFactory.class); 
	private String conceptType;
	private PdfFactoryRegistry registry;
	
	public BasicPdfFactory(String conceptType) {
		this.conceptType = conceptType;
	}

	protected PdfFactoryRegistry getRegistry() {
		return registry;
	}

	public boolean isApplicable(String type) {
		return conceptType.equals(type);
	}
	
	public void setRegistry(PdfFactoryRegistry registry) {
		this.registry = registry;
	}

	public void writeElement(C concept, Document doc, int indentation) throws DocumentException {
		if (null == doc) {
			doc = new Document();
		}
		if (!doc.isOpen()) {
			doc.open();
		}
		writeConcept(concept,doc,indentation);
	}

	protected abstract void writeConcept(C concept, Document doc, int indentation) throws DocumentException;

	public String getType() {
		return conceptType;
	}

	public boolean isApplicable(Object concept) {
		return getConceptClass().isInstance(concept);
	}
	
	protected PdfPCell createNumberCell(Number number){
		PdfPCell cell = new PdfPCell(new Phrase(new Chunk(number.toString(), FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL))));
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		return cell;
	}
	
	protected String getIndentation(int indentation, String s){
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < indentation; i++) {
			sb.append(s);
		}
		return sb.toString();
	}
	
	protected PdfPCell createTextCell(String text){
		return createTextCell(text,1);
	}
	
	protected PdfPCell createTextCell(String text,int colSpan){
		if (null == text) {
			text = "";
		}
		PdfPCell cell = new PdfPCell(new Phrase(new Chunk(text, FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL))));
		cell.setHorizontalAlignment(Element.ALIGN_LEFT);
		cell.setColspan(colSpan);
		return cell;
	}

	protected PdfPCell createLabelCell(String label){
		PdfPCell cell = new PdfPCell(new Phrase(new Chunk(label, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10, Font.NORMAL))));
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		return cell;
	}
}
